package com.huilian.iotbox.admin.controller;

import com.huilian.iotbox.admin.service.CacheService;
import com.huilian.iotbox.admin.service.UserService;
import com.huilian.iotbox.data.common.ServerResponse;
import com.huilian.iotbox.data.controller.BaseController;
import com.huilian.iotbox.data.enums.RoleEnum;
import com.huilian.iotbox.data.vo.CacheVo;
import com.huilian.iotbox.data.vo.UserInfo;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author 曹畅
 * @date 2020/4/17
 */
@RestController
@RequestMapping("/api/cache")
public class CacheController extends BaseController {

    @Resource
    CacheService cacheService;

    @Resource
    private UserService userService;

    @GetMapping("/findList")
    public ServerResponse findList(CacheVo cacheVo) {
        return cacheService.findList(cacheVo);
    }

    @GetMapping("/findListByKey")
    public ServerResponse findListByKey(CacheVo cacheVo, HttpServletRequest request) {
        UserInfo userInfo = userService.getLoginUserInfo(request);
        return cacheService.findListByKey(cacheVo);
    }

    @GetMapping("/findCacheDetail")
    public ServerResponse findCacheDetail(CacheVo cacheVo, HttpServletRequest request) {
        UserInfo userInfo = userService.getLoginUserInfo(request);
        return cacheService.findCacheDetail(cacheVo);
    }

    @DeleteMapping("/deleteCache/{key}")
    public ServerResponse deleteCache(@PathVariable String key, HttpServletRequest request) {
        UserInfo userInfo = userService.getLoginUserInfo(request);
        return cacheService.deleteCache(key);
    }

    @DeleteMapping("/deleteKeyPrefix/{id}")
    public ServerResponse deleteKeyPrefix(@PathVariable Integer id, HttpServletRequest request) {
        UserInfo userInfo = userService.getLoginUserInfo(request);
        return cacheService.deleteKeyPrefix(id);
    }

    @PostMapping()
    public ServerResponse insert(@RequestBody CacheVo cacheVo, HttpServletRequest request) {
        UserInfo userInfo = userService.getLoginUserInfo(request);
        if (!RoleEnum.SUPER_ADMINISTRATOR.getRoleId().equals(userInfo.getRoleId())) {
            return ServerResponse.createByErrorMessage("您没有权限");
        }
        return ServerResponse.createBySuccess(cacheService.insert(cacheVo));
    }
}
